import { GlobalData } from '/store/state'
import { getServer, getAppId } from '/store/mutations'
import { getDomoUser } from '/store/actions'
import { $event } from '/utils'
import { knowledgeApi } from '/api/konwledge'
//@ts-ignore
import getMessage from 'ts-msg-handler'

Page({
  data: {
    knowledgeId: '',
    top: GlobalData.menuRect.top,
    height: GlobalData.menuRect.height,
    currencyName: GlobalData.currencyName,
    // 收货地址
    realname: '',
    phone: '',
    province: '',
    city: '',
    country: '',
    detail: '',
    info: {} as any,
    count: 1,
    countPrice: 0,
    countPrices: 0,
    score: 0,
    exchangeRate: 0.1,
    reMarks: '',
    userScore: 0,
    needScore: 0,
    payToast: false,
    paySuccess: true,
    markerPrice: 0,
    submitLock: false,
  },
  async onLoad(options: any) {
    wx.hideShareMenu()
    const info = await knowledgeApi.getKnowledgeDetail(options.id)
    this.setData({
      knowledgeId: options.id,
      info,
    })
    const form = wx.getStorageSync('address')
    this.setData(form)
    this.getPrice()
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    getDomoUser()
    this.getPosition()
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      exchangeRate: GlobalData.currency.settings['recharge-ratio'],
      currencyName: GlobalData.currencyName,
      top: GlobalData.menuRect.top,
      height: GlobalData.menuRect.height,
    })
  },
  chooseAddress() {
    const chooseAddress = () => {
      wx.chooseAddress({
        success: (res) => {
          const form = {
            realname: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            country: res.countyName,
            detail: res.detailInfo,
          }
          wx.setStorageSync('address', form)

          this.setData(form)
        },
      })
    }

    // 获取收货地址授权信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.address'] === false) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address'] === false) {
                wx.showToast({ title: '请允许使用您的收货地址', icon: 'none' })
              } else {
                chooseAddress()
              }
            },
          })
          return
        }
      },
    })
    chooseAddress()
  },
  onInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      reMarks: e.detail.value,
    })
  },
  /** 计算金额 */
  getPrice() {
    const countPrice = (this.data.info.price * this.data.count) / 100
    const countPrices = this.data.info.price * this.data.count
    const markerPrice = this.data.info.price + this.data.info.score / this.data.exchangeRate
    const excludes = wx.getStorageSync(`${getServer()}/logged`).data || []
    const userScore = excludes.currency.sum
    const needScore = this.data.info.score * this.data.count
    const score = needScore > userScore ? userScore : needScore
    this.setData({
      countPrice,
      countPrices,
      score,
      userScore,
      needScore,
      markerPrice,
    })
  },
  openConfirm() {
    // if (
    //   this.data.info.remote_areas &&
    //   this.data.info.remote_areas.includes(this.data.province.slice(0, 2))
    // ) {
    //   wx.showToast({ title: '抱歉，偏远地区暂不发货，感谢理解', icon: 'none' })
    //   return
    // }
    if (this.data.info.buying_read) {
      this.setData({ showConfirm: true })
    } else {
      this.onSubmit()
    }
  },
  async onSubmit() {
    if (this.data.submitLock) {
      return
    }
    this.closeConfirm()
    this.setData({ submitLock: true })
    try {
      const payInfo = await knowledgeApi.postKnowledgeOrder({
        knowledge_id: this.data.knowledgeId,
        user_remark: this.data.reMarks,
        pay_score: this.data.score,
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
      })
      if (payInfo.pay_amount === 0) {
        this.payShowToast(true)
        return
      }
      wx.requestPayment({
        ...payInfo.pay_data,
        success: () => {
          this.payShowToast(true)
        },
        fail: () => {
          this.payShowToast(false)
        },
      })
    } catch (error) {
      this.setData({ submitLock: false })
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
      console.log(error)
    }
  },
  closeConfirm() {
    this.setData({ showConfirm: false })
  },
  payShowToast(success: boolean) {
    this.setData({
      payToast: true,
      paySuccess: success,
      submitLock: success,
    })
  },
  closePayShow() {
    this.setData({ payToast: false })
    wx.navigateBack({ delta: 1 })
  },
  toHome() {
    wx.switchTab({
      url: '/pages/feed/list/list',
    })
  },
})
